package com.example.demo.RoomDeal;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;


//游戏房间管理
@Component
public class RoomManager {
    //使用哈希表来存储每个房间
    private ConcurrentHashMap<String, Room> rooms=new ConcurrentHashMap<>();

    private ConcurrentHashMap<Integer,String> userIdToRoomId=new ConcurrentHashMap<>();


    public void add(Room room,Integer userId1,Integer userId2){
        rooms.put(room.getRoomId(),room);
        userIdToRoomId.put(userId1,room.getRoomId());
        userIdToRoomId.put(userId2,room.getRoomId());
    }
    public void remove(String roomId,Integer userId1,Integer userId2){
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public Room getRoomByRoomId(String roomId){
        Room room = rooms.get(roomId);
        return room;
    }

    public Room getRoomByUserId(Integer userId){
        String room = userIdToRoomId.get(userId);
        if (room==null){
            return null;
        }
       return rooms.get(room);
    }
}
